package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.mapper.TaskOperationLogMapper;
import com.yupi.springbootinit.model.entity.TaskOperationLog;
import com.yupi.springbootinit.model.vo.TaskOperationLogVO;
import com.yupi.springbootinit.service.TaskOperationLogService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 任务操作日志服务实现
 */
@Service
public class TaskOperationLogServiceImpl implements TaskOperationLogService {

    @Resource
    private TaskOperationLogMapper mapper;

    @Override
    public void log(Long taskId, String operationType, String operatorName, String remark, LocalDateTime operationTime) {
        TaskOperationLog log = new TaskOperationLog();
        log.setTaskId(taskId);
        log.setOperationType(operationType);
        log.setOperatorName(operatorName);
        log.setRemark(remark);
        log.setOperationTime(operationTime != null ? operationTime : LocalDateTime.now());
        log.setCreatedAt(LocalDateTime.now());
        mapper.insert(log);
    }

    @Override
    public List<TaskOperationLogVO> listByTaskId(Long taskId) {
        QueryWrapper<TaskOperationLog> qw = new QueryWrapper<>();
        qw.eq("task_id", taskId).orderByDesc("operation_time");
        List<TaskOperationLog> list = mapper.selectList(qw);
        return list.stream().map(item -> {
            TaskOperationLogVO vo = new TaskOperationLogVO();
            vo.setOperationType(item.getOperationType());
            vo.setOperatorName(item.getOperatorName());
            vo.setOperationTime(item.getOperationTime() != null ? item.getOperationTime().toString() : null);
            vo.setRemark(item.getRemark());
            return vo;
        }).collect(Collectors.toList());
    }
}